package com.example.common.base

import androidx.annotation.Nullable
import androidx.recyclerview.widget.RecyclerView


abstract class BaseAdapter<T> : RecyclerView.Adapter<BaseViewHolder> {

    var mData: ArrayList<T>? = ArrayList()

    constructor() {

    }


    fun updateData(data: List<T>) {
        this.mData?.clear()
        this.mData?.addAll(data)
        notifyDataSetChanged()
    }

    fun <B> upDataItem(position: Int, b: B) {
        this.mData!![position] = b as T
        notifyDataSetChanged()
    }

    // 添加新的Item
    fun addNewItem(item: T) {
        if (mData == null) {
            mData = ArrayList()
        }
        mData!!.add(0, item)
        notifyItemInserted(0)
    }

    fun getItem(position: Int): T {
        return mData!![position]
    }

    // 删除Item
    fun deleteItem(position: Int) {
        if (mData == null || mData!!.isEmpty()) {
            return
        }
        mData!!.removeAt(position)
        notifyItemRemoved(position)
    }

    override fun getItemCount(): Int {
        return if (mData == null) 0 else mData!!.size
    }

}

fun <T : RecyclerView.ViewHolder?> RecyclerView.setup(@Nullable adapter: RecyclerView.Adapter<T>) {
    if (layoutManager == null) {
        layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
    }
    this.adapter = adapter
}

